﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;

using NUnit.Framework;
using EasyNet.Solr;
using EasyNet.Solr.Commons;
using EasyNet.Solr.Impl;
using EasyNet.Solr.Commons.Params;
using System.Reflection;

namespace SolrExample.Tests.EasyNetSolr
{
    /// <summary>
    /// Summary description for UnitTest1
    /// </summary>
    [TestFixture]
    public class UnitTest1
    {
        private CommitOptions commitOptions = new CommitOptions();        
        private OptimizeOptions optimizeOptions = new OptimizeOptions();
        private static readonly ISolrResponseParser<NamedList, ResponseHeader> binaryResponseHeaderParser = new BinaryResponseHeaderParser();

        private static readonly IObjectSerializer<SolrIndexRecord> objectSerializer = new SolrObjectSerializer();
        private static readonly IUpdateParametersConvert<NamedList> updateParametersConvert = new BinaryUpdateParametersConvert();
        private ISolrUpdateConnection<NamedList, NamedList> solrUpdateConnection;
        private ISolrUpdateOperations<NamedList> updateOperations;

        private ISolrReadonlyConnection<NamedList> solrQueryConnection;
        private ISolrQueryOperations<NamedList> queryOperations;
        private static readonly ISolrResponseParser<NamedList, QueryResults<SolrSearchResultRecord>> binaryQueryResultsParser = new BinaryQueryResultsParser<SolrSearchResultRecord>(new SolrObjectDeSerializer());
        private static readonly ISolrResponseParser<NamedList, IDictionary<string, IDictionary<string, IList<string>>>> binaryHighlightingParser = new BinaryHighlightingParser();
        private IDictionary<string, IDictionary<string, IList<string>>> hightlightResult;
        private static readonly ISolrResponseParser<NamedList, IDictionary<string, IList<FacetField>>> binaryFacetFieldsParser = new BinaryFacetFieldsParser();
        private IDictionary<string, IList<FacetField>> facetResult;

        [TestFixtureSetUp]
        public void InitializeAllTests()
        {
            //string solrCoreUrl = "http://127.0.0.1:8080/solr-HDM/HK";
            string solrCoreUrl = "http://127.0.0.1:8080/solr-Example/HK";
            solrUpdateConnection = new SolrUpdateConnection<NamedList, NamedList>() { ServerUrl = solrCoreUrl };
            solrQueryConnection = new SolrReadonlyConnection<NamedList>() { ServerUrl = solrCoreUrl };
        }

        [Test]
        public void Test1()
        {
            updateOperations = new SolrUpdateOperations<NamedList, NamedList>(solrUpdateConnection, updateParametersConvert) { 
                ResponseWriter="javabin"
            };
            
            IList<SolrIndexRecord> solrIndexRecords = getSolrIndexRecords();

            if (solrIndexRecords != null && solrIndexRecords.Count > 0)
            {
                var result = updateOperations.Update(new UpdateOptions()
                {
                    DelByQ = new string[] { "*:*" },
                    CommitOptions = commitOptions                                        
                });
                var header = binaryResponseHeaderParser.Parse(result);
                Console.WriteLine("Delete Status:{0} QTime:{1}", header.Status, header.QTime);

                result = updateOperations.Update(new UpdateOptions()
                {
                    OptimizeOptions = optimizeOptions,
                    Docs = objectSerializer.Serialize(solrIndexRecords)
                });
                header = binaryResponseHeaderParser.Parse(result); 
                Console.WriteLine("Update Status:{0} QTime:{1}", header.Status, header.QTime);
                
            }
        }

        [Test]
        public void Test2() {
            queryOperations = new SolrQueryOperations<NamedList>(solrQueryConnection) { ResponseWriter = "javabin" };

            string searchQuery = "name:name";
            SolrQuery solrQuery = new SolrQuery(searchQuery);

            IDictionary<string, ICollection<string>> solrQueryOption = new Dictionary<string, ICollection<string>>();
            solrQueryOption[CommonParams.WT] = new string[] { "javabin" };
            solrQueryOption[CommonParams.FL] = new string[] { "id", "name" };
            solrQueryOption[CommonParams.START] = new string[] { "0" };
            solrQueryOption[CommonParams.ROWS] = new string[] { "100" };
            solrQueryOption[CommonParams.SORT] = new string[] { "id desc,name desc" };

            solrQueryOption[HighlightParams.HIGHLIGHT] = new string[] { "true" };
            solrQueryOption[HighlightParams.FIELDS] = new string[] { "id" };

            NamedList searchResult = queryOperations.Query(solrQuery, solrQueryOption);
            
            //解析返回头信息
            var responseHeader = binaryResponseHeaderParser.Parse(searchResult);
            Console.WriteLine("Query Status:{0} QTime:{1}", responseHeader.Status, responseHeader.QTime);
            
            //解析查询结果            
            QueryResults<SolrSearchResultRecord> queryResult = binaryQueryResultsParser.Parse(searchResult);
            Console.WriteLine("Total:{0} Result:{1}", queryResult.NumFound, queryResult.Count);

            //解析高亮
            hightlightResult = binaryHighlightingParser.Parse(searchResult);

            facetResult = binaryFacetFieldsParser.Parse(searchResult);

        }

        [Test]
        public void test3() {
            string s = "IList<string>".Substring(0,5);
            Console.WriteLine(s);
        }

        private static Dictionary<string, PropertyInfo> GetField<T>(T queryClass)
        {
            PropertyInfo[] instancePropertyInfos = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);

            Type[] interfaceTypes = typeof(T).GetInterfaces();
            List<PropertyInfo> allPropertyInfos = new List<PropertyInfo>();

            foreach (Type type in interfaceTypes)
            {
                allPropertyInfos.AddRange(type.GetProperties());
            }

            allPropertyInfos.AddRange(instancePropertyInfos);

            Dictionary<string, PropertyInfo> distinctPropertyInfos = new Dictionary<string, PropertyInfo>();
            //List<PropertyInfo> distinctPropertyInfos = new List<PropertyInfo>();
            foreach (PropertyInfo pi in allPropertyInfos)
            {
                var piCurrent = distinctPropertyInfos.SingleOrDefault(i => i.Value.Name.Equals(pi.Name, StringComparison.OrdinalIgnoreCase));
                if (null == piCurrent.Value)
                {
                    distinctPropertyInfos.Add(pi.Name, pi);
                }
            }

            return distinctPropertyInfos;
        }


        [TestFixtureTearDown]
        public void CleanupAllTests() { }


        public IList<SolrIndexRecord> getSolrIndexRecords() {
            IList<SolrIndexRecord> list = new List<SolrIndexRecord>();
            for (var i = 0; i < 100; i++) {
                list.Add(new SolrIndexRecord()
                {
                    Id = i,
                    Name = "Name" + i,
                    Tag = new string[] { "tag" + i, "tag_" + i },
                    CreatedTime = DateTime.Now
                });
            }
            return list;
        }
    }
       
}
